package com.simtop.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import static com.simtop.pojo.All.statusaus;

/**
 * @ClassName FileUploadAndDownload
 * @Description TODO   文件上传下载工具类
 * @Author lvyongwei
 * @Date 2020-05-21 10:16
 **/
@Component
@Configuration
public class FileUploadAndDownload {


    /**
     *  filePath 即存放路径
     * 获取文件要上传的绝对路径 (配置信息里的)
     *    例如：C:\Users\Administrator\Desktop
     */
    @Value("${file.profile}")
    private String filePath;

    private Logger logger = LoggerFactory.getLogger(FileUploadAndDownload.class);


    /**
     * 文件上传的方法
     * @param file
     * @return 返回文件存储名
     */
    public String upload(MultipartFile file){
        File localFile=new File(filePath+"\\profile");
        if(!localFile.exists()){//如果文件夹不存在
            localFile.mkdir();//创建文件夹
        }
        //获取文件名
        //String str= UUID.randomUUID().toString();
        //获取文件名
        String filename=UUID.randomUUID().toString()+file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        //创建文件存放路径
        File uploadfile=new File(filePath+"\\profile"+"\\"+filename);
        //System.err.println(filePath);
        try {
            //文件上传操作
            file.transferTo(uploadfile);
            logger.info("上传项目资料成功{}",filename);
            return "\\profile\\"+filename;
        } catch (IOException e) {
            e.printStackTrace();
            logger.error("上传项目资料失败{}",filename);
            return null;
        }
    }

    /**
     * 文件上传的方法
     * @param file
     * @return 返回文件存储名
     */
    public String upload2(MultipartFile file, String path) {
        File localFile=new File(filePath+"\\profile\\"+path);
        if(!localFile.exists()){
            localFile.mkdirs();
        }
        //获取文件名
        String name=file.getOriginalFilename();
        System.out.println(name);
        String suffix = name.substring(name.indexOf("."),name.length());
        System.out.println(suffix);

        String []asa = name.split("\\.");
        String s = asa[asa.length - 1];
        String filename = UUID.randomUUID().toString() + "." +s;



        statusaus = filename ;

        //创建文件存放路径
        File uploadfile=new File(filePath+"\\profile"+"\\"+path+"\\"+filename);
        //文件上传操作
        try {
            //文件上传操作
            file.transferTo(uploadfile);
            logger.info("上传项目资料成功{}",filename);
            return "\\profile\\"+path+"\\"+filename;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("上传项目资料失败{}",filename);
            return null;
        }
    }

    /**
     * 文件下载的方法
     * @param path    数据库存放的文件名
     */
    public void download(HttpServletRequest request, HttpServletResponse response, String path) throws IOException {
        // 获取资源地址
        String downloadPath = filePath + path;
        response.setCharacterEncoding("utf-8");
        response.setContentType("multipart/form-data");
        response.setHeader("Content-Disposition",
                "attachment;fileName=" + setFileDownloadHeader(request, path));
        writeBytes(downloadPath, response.getOutputStream());
    }




    public static String setFileDownloadHeader(HttpServletRequest request, String fileName) throws UnsupportedEncodingException
    {
        final String agent = request.getHeader("USER-AGENT");
        String filename = fileName;
        if (agent.contains("MSIE"))
        {
            // IE浏览器
            filename = URLEncoder.encode(filename, "utf-8");
            filename = filename.replace("+", " ");
        }
        else if (agent.contains("Firefox"))
        {
            // 火狐浏览器
            filename = new String(fileName.getBytes(), "ISO8859-1");
        }
        else if (agent.contains("Chrome"))
        {
            // google浏览器
            filename = URLEncoder.encode(filename, "utf-8");
        }
        else
        {
            // 其它浏览器
            filename = URLEncoder.encode(filename, "utf-8");
        }
        return filename;
    }


    public static void writeBytes(String filePath, OutputStream os) throws IOException
    {
        FileInputStream fis = null;
        try
        {
            File file = new File(filePath);
            if (!file.exists())
            {
                throw new FileNotFoundException(filePath);
            }
            fis = new FileInputStream(file);
            byte[] b = new byte[1024];
            int length;
            while ((length = fis.read(b)) > 0)
            {
                os.write(b, 0, length);
            }
        }
        catch (IOException e)
        {
            throw e;
        }
        finally
        {
            if (os != null)
            {
                try
                {
                    os.close();
                }
                catch (IOException e1)
                {
                    e1.printStackTrace();
                }
            }
            if (fis != null)
            {
                try
                {
                    fis.close();
                }
                catch (IOException e1)
                {
                    e1.printStackTrace();
                }
            }
        }
    }

    /**
     * 多个文件下载    （先压缩文件再下载）
     * @param request
     * @param response
     * @param fileNames  多个文件存储路径
     * @return
     */
    public void downloadZip(HttpServletRequest request, HttpServletResponse response, String[] fileNames) throws IOException {
        //判断是否为空
        if(fileNames.length<=0){
            return ;
        }
        /**
         * 获取多个文件，生成压缩文件
         */
        //存储所有文件的绝对路径
        List<File> list=new ArrayList<File>();
        for(String fileName:fileNames){
            list.add(new File(filePath+fileName));
        }
        //设置压缩文件的名称
        String zipName=UUID.randomUUID().toString()+".zip";
        //创建File对象
        File zipFile=new File(filePath+"\\"+zipName);
        //临时存储zip文件
        byte[] bArr=new byte[1024];
        try {
            //创建输出流对象
            ZipOutputStream out=new ZipOutputStream(new FileOutputStream(zipFile));
            for(int i=0;i<list.size();i++){
                FileInputStream in=new FileInputStream(list.get(i));
                out.putNextEntry(new ZipEntry(list.get(i).getName()));
                int len;
                while((len=in.read(bArr))>0){
                    out.write(bArr,0,len);
                }
                out.closeEntry();
                in.close();
            }
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        /**
         * 下载压缩文件
         */
        String downloadPath = filePath +"/"+ zipName;
        response.setCharacterEncoding("utf-8");
        response.setContentType("multipart/form-data");
        response.setHeader("Content-Disposition",
                "attachment;fileName=" + FileUploadAndDownload.setFileDownloadHeader(request, zipName));
        File file=new File(downloadPath);
        FileInputStream in = new FileInputStream(file);
        ServletOutputStream out = response.getOutputStream();
        byte[] buff =  new byte[1024];
        int len2=0;
        while ((len2 = in.read(buff)) != -1) {
            out.write(buff, 0, len2);
        }
        in.close();
        //将临时存储的zip文件删除
        file.delete();
    }
}
